package com.wangyonghui.service.user.service.impl;

import com.wangyonghui.service.user.dao.UserRepository;
import com.wangyonghui.service.user.entity.User;
import com.wangyonghui.service.user.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserRepository userRepository;
    @Override
    public Page<User> list(Integer pageNum, Integer pageSize, User user) {
        ArrayList<Predicate> list = new ArrayList<>();
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
                if(user!=null && user.getName()!=null){
                    Predicate predicate = cb.like(root.get("name"), "%" + user.getName() + "%");
                    list.add(predicate);
                }
                return cb.and(list.toArray(new Predicate[list.size()]));
            }
        };
        PageRequest pageable = PageRequest.of(pageNum - 1, pageSize);
        return userRepository.findAll(specification,pageable);
    }

    @Override
    public Object save(User user) {

        System.err.print("添加收到的数据"+user);
        return userRepository.save(user);
    }

    @Override
    public void delete(Integer[] ids) {
        if (ids!=null && ids.length>0){
            for (Integer id:ids){
                userRepository.deleteById(id);
            }
        }
    }

}
